//
//  LoginController.m
//  卖空Japan
//
//  Created by mac on 2019/7/2.
//  Copyright © 2019 mac. All rights reserved.
//

#import "LoginController.h"

#define API_ROOT @"https://weapp.whwangdoudou.cn"

#define API_URL [API_ROOT stringByAppendingString:@"/weapp.php"]

@interface LoginController () <UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITextField *nameTextField;
@property (weak, nonatomic) IBOutlet UITextField *passwordTextField;

@property (weak, nonatomic) IBOutlet UIButton *sendCodeButton;

@property(strong,nonatomic) NSTimer *timer;

@property(assign,nonatomic) NSInteger count;

@end

@implementation LoginController


- (BOOL)prefersStatusBarHidden {
    
    return YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    //通过CAGradientLayer 设置渐变的背景。
    CAGradientLayer *layer = [CAGradientLayer new];
    //colors存放渐变的颜色的数组
    layer.colors=@[(__bridge id)[UIColor colorWithRed:56/255.0 green:186/255.0 blue:208/255.0 alpha:1].CGColor,(__bridge id)[UIColor colorWithRed:42/255.0 green:108/255.0 blue:218/255.0 alpha:1].CGColor];
    /**
     * 起点和终点表示的坐标系位置，(0,0)表示左上角，(1,1)表示右下角
     */
    layer.startPoint = CGPointMake(0, 0);
    layer.endPoint = CGPointMake(0, 1.0);
    layer.frame = self.view.bounds;
    [self.view.layer insertSublayer:layer atIndex:0];
    
    _nameTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入手机号" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16],NSForegroundColorAttributeName:[UIColor whiteColor]}];
    _passwordTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入验证码" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16],NSForegroundColorAttributeName:[UIColor whiteColor]}];
    
    [_sendCodeButton.layer setBorderColor:[UIColor grayColor].CGColor];
    [_sendCodeButton.layer setBorderWidth:1];
    
    _sendCodeButton.layer.cornerRadius = 3.0f;
    _sendCodeButton.layer.masksToBounds = YES;
}
    
- (IBAction)cancenBtnAction:(id)sender {
    
    [self dismissViewControllerAnimated:YES completion:nil];
}
    
//获取验证码
- (IBAction)showAndHidePassword:(UIButton *)sender {
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"m"] = @"send_code";
    param[@"phone"] = _nameTextField.text;
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.requestSerializer setValue:@"multipart/form-data;" forHTTPHeaderField:@"Content-Type"];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
    [manager POST:API_URL parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *resultDic = (NSDictionary *)responseObject;
        if ([resultDic[@"r"] isEqual:@(0)]) {
            [self timeFailBeginFrom:60];
        }else {
            [SVProgressHUD showErrorWithStatus:resultDic[@"errmsg"]];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error:%@",error.localizedDescription);
    }];
}

- (IBAction)loginBtnAction:(UIButton *)sender {

    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"m"] = @"ios_check_code";
    param[@"phone"] = _nameTextField.text;
    param[@"code"] = _passwordTextField.text;
//    param[@"channel"] = @"";
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
    [SVProgressHUD showWithStatus:@"努力登录中..."];
    [manager POST:API_URL parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [SVProgressHUD dismiss];
        NSDictionary *resultDic = (NSDictionary *)responseObject;
        if ([resultDic[@"r"] isEqual:@(0)]) {
            NSUserDefaults *userDefa = [NSUserDefaults standardUserDefaults];
            [userDefa setObject:resultDic[@"uid"] forKey:kPhone];
            [self dismissViewControllerAnimated:YES completion:nil];
        }else {
           [SVProgressHUD showErrorWithStatus:resultDic[@"errmsg"]];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [SVProgressHUD dismiss];
    }];
}

- (IBAction)registerBtnAction:(id)sender {
    
    [self dismissViewControllerAnimated:YES completion:nil];
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    [self.view endEditing:YES];
}

#pragma mark - 添加定时器
- (void)timeFailBeginFrom:(NSInteger)timeCount
{
    self.count = timeCount;
    _sendCodeButton.enabled = NO;
    // 加1个定时器
    if (!self.timer) {
       self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeDown) userInfo: nil repeats:YES];
    }
}

#pragma mark - 定时器事件
- (void)timeDown
{
    if (self.count != 1){
        
        self.count -=1;
        _sendCodeButton.enabled = NO;
        [_sendCodeButton setTitle:[NSString stringWithFormat:@"剩余%zd秒", self.count] forState:UIControlStateNormal];
        
    } else {
        
        _sendCodeButton.enabled = YES;
        [_sendCodeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
        [self.timer invalidate];
    }
    
}


- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.timer invalidate];
    self.timer = nil;
}

@end
